package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */

@EnableConfigurationProperties(value = MinioProperties.class)
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) {
        log.info("【0】上传开始，原始文件名：{}", file.getOriginalFilename());

        try (InputStream is = file.getInputStream()) {   // ← try-with-resources 自动关流
            /* ---------- 1. 创建客户端 ---------- */
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            log.info("【1】MinioClient 创建成功");

            /* ---------- 2. 桶存在检查 ---------- */
            boolean isExist = minioClient
                    .bucketExists(BucketExistsArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .build());
            log.info("【2】桶存在检查结果：{}", isExist);

            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build());
                log.info("【3】桶已创建");
            }

            /* ---------- 3. 构造对象名 ---------- */
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix = UUID.randomUUID().toString().replace("-", "");
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            String fileName = format + "/" + prefix + suffix;
            log.info("【4】生成对象名：{}", fileName);

            /* ---------- 4. 真正上传 ---------- */
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(is, file.getSize(), -1)
                            .contentType(file.getContentType()) // 让浏览器能预览
                            .build());
            log.info("【5】putObject 调用完成");

            /* ---------- 5. 返回 URL ---------- */
            String url = minioProperties.getEndpoint()
                    + "/" + minioProperties.getBucketName()
                    + "/" + fileName;
            log.info("【6】返回 URL：{}", url);
            return url;

        } catch (Exception e) {
            log.error("【X】上传过程异常", e);   // 关键：把完整堆栈打出来
            throw new RuntimeException("上传失败：" + e.getMessage()); // 让控制器返回 500
        }
    }

//    public static void main(String[] args) {
//        String fileName = "豆豆.jpg";
//        int index = fileName.lastIndexOf(".");
//        System.out.println("index = " + index);
//        //获取文件名的后缀
//        String substring = fileName.substring(index);
//        System.out.println("substring = " + substring);
//        //使用UUID随机生成一个字符串作为文件名
//        String uuid = UUID.randomUUID().toString().replaceAll("-","");
//        System.out.println("uuid = " + uuid);
//    }
}